package com.zxp.utils.configParseUtils;

import org.yaml.snakeyaml.Yaml;

import java.io.IOException;
import java.io.InputStream;
import java.util.Map;

public class YamlConfigReader {

    private static final String CONFIG_FILE = "config.yaml";
    private static Map<String, Object> config;

    static {
        loadConfig();
    }

    private static void loadConfig() {
        Yaml yaml = new Yaml();
        try (InputStream input = YamlConfigReader.class.getClassLoader().getResourceAsStream(CONFIG_FILE)) {
            if (input == null) {
                throw new RuntimeException("Unable to find " + CONFIG_FILE);
            }

            // load YAML file into a Map
            config = yaml.load(input);

        } catch (IOException e) {
            throw new RuntimeException("Error loading " + CONFIG_FILE, e);
        }
    }

    public static String getString(String key) {
        Object value = getConfigValue(key);

        if (value instanceof String) {
            return (String) value;
        } else {
            throw new RuntimeException("Config key '" + key + "' is not a string value in " + CONFIG_FILE);
        }
    }

    public static int getInt(String key) {
        Object value = getConfigValue(key);

        if (value instanceof Integer) {
            return (Integer) value;
        } else {
            throw new RuntimeException("Config key '" + key + "' is not an integer value in " + CONFIG_FILE);
        }
    }

    public static boolean getBoolean(String key) {
        Object value = getConfigValue(key);

        if (value instanceof Boolean) {
            return (Boolean) value;
        } else {
            throw new RuntimeException("Config key '" + key + "' is not a boolean value in " + CONFIG_FILE);
        }
    }

    @SuppressWarnings("unchecked")
    private static Object getConfigValue(String key) {
        Object value = config;

        for (String part : key.split("\\.")) {
            if (value instanceof Map) {
                value = ((Map<String, Object>) value).get(part);
            } else {
                throw new RuntimeException("Config key '" + key + "' not found in " + CONFIG_FILE);
            }
        }

        return value;
    }


    public static void main(String[] args) {
        // Example usage:
        String databaseUrl = getString("database.url");
        String username = getString("database.username");
        String password = getString("database.password");

        System.out.println(getString("database.driver.name"));
        System.out.println("Database URL: " + databaseUrl);
        System.out.println("Username: " + username);
        System.out.println("Password: " + password);
    }
}
